package mybatis.sqlsession.defaults;

import dao.IUserDao;
import mybatis.cfg.Configuration;
import mybatis.sqlsession.SqlSession;
import mybatis.sqlsession.proxy.MapperProxy;
import mybatis.utils.DataSourceUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.sql.Connection;

public class DefaultsSqlSession implements SqlSession {
    private Configuration cfg;
    private Connection connection;

    public DefaultsSqlSession(Configuration cfg){
        this.cfg = cfg;
        connection = DataSourceUtil.getConnection(cfg);
    }


    /**
     * 用于创建代理对象
     * @param iUserDaoClass
     * @return
     */
    @Override
    public <T> T getMapper(Class<IUserDao> iUserDaoClass) {

        return (T) Proxy.newProxyInstance(iUserDaoClass.getClassLoader(),
                new Class[]{iUserDaoClass}, new MapperProxy(cfg.getMappers(),connection));
    }

    /**
     * 用于释放资源
     */
    @Override
    public void close() {

    }
}
